<?php

namespace app\admin\controller;

use app\common\lib\Qiniu;
use app\lib\traits\Image as imageTrait;
use app\common\Helper;
use app\admin\model\Advertise as AdvertiseMdl;
use app\admin\model\Advertiselocal;
use app\admin\model\Image;

use think\Db;
use think\Exception;
use think\Request;

/**
 * 广告
 */
class Advertise extends Base
{

    public function _initialize()
    {
        parent::_initialize();

        $this->model = new AdvertiseMdl();
    }

    /**
     * 列表
     */
    public function getList(){
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;

        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $where = [
            'status' => ['neq', 3],
        ];
        $model = $this->model;
        $order = 'putAwayTime ASC';
        $result = $model->where($where)->limit($start, $length)->order($order)->select();
        $total = $model->where($where)->count();

        if (!$result) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关广告');
        }

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
    }

    /**
     * 添加/编辑 保存
     */
    public function save(){
        $param = self::getHttpParam();
        $model = $this->model;

        if (empty($param->advertiseTitle)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'advertiseTitle 不能为空');
        }
        if (empty($param->imgUrl)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'imgUrl 不能为空');
        }
        if (empty($param->advertiselocalId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'advertiselocalId 不能为空');
        }
        /*if (empty($param->advertiseUrlStatus) && $param->advertiseUrlStatus != 0) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'advertiseUrlStatus 不能为空');
        }
        if (!in_array($param->advertiseUrlStatus, [2, 3])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'advertiseUrlStatus 类型不正确');
        }*/

        Db::startTrans();
        $data = (array)$param;
        $data['advertiseImgUrl'] = $param->imgUrl;
        if (!empty($param->advertiseId)) {
            // 修改
            $id = $param->advertiseId;
            $result = $model->allowField(true)->save($data, ['id' => $id]);

            if($result === false){
                Db::rollback();
                return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $model->getError());
            }
            $connectData = [
                'advertiseId' => $data['id'],
                'advertiseLocalId' => $param->advertiselocalId
            ];
            db('advertiselocalconnect')->insert($connectData);

            Db::commit();
            // Query执行后的操作
            $model->_after_update($data);
        } else {
            // 新增
            $data['id'] = Helper::getUUID();
            $data['createTime'] = date('Y-m-d H:i:s');
            $result = $model->save($data);

            if ($result !== false) {
                $connectData = [
                    'advertiseId' => $data['id'],
                    'advertiseLocalId' => $param->advertiselocalId
                ];
                db('advertiselocalconnect')->insert($connectData);

                // 图片
                $res = true;
                if(isset($param->imgIds) && $param->imgIds) {
                    $imgIds = (array) $param->imgIds;
                    foreach($imgIds as $key => $imgId){
                        $res = Image::where(['id' => $imgId])->update(['relatedId' => $data['id'], 'controller' => 'Advertise', 'relatedTable' => 'advertise', 'tag' => 'imglist', 'sorting' => $key]);
                    }
                }
                if(!$res){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::NOT_DATA, '图片保存失败');
                }
            } else {
                Db::rollback();
                return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $model->getError());
            }

            Db::commit();
            // Query执行后的操作
            $model->_after_insert($data);
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, '保存成功');
    }

    /**
     * 检查是否已有投放
     */
    public function checkExist(){
        $param = self::getHttpParam();
        $model = db('advertiselocalconnect');

        if (empty($param->advertiselocalId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'advertiselocalId 不能为空');
        }

        $where = [
            'advertiseLocalId' => $param->advertiselocalId
        ];
        $join = [
            ['advertise ad', 'ad.id = a.advertiseId']
        ];
        $field = 'ad.*';
        $info = $model->alias('a')->where($where)->join($join)->field($field)->find();

        if ($info) {
            $putAwayTime = strtotime($info['putAwayTime']) + $info['circleTime'] * 24*3600;
            $putAwayTime = date('Y-m-d H:i:s');

            return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $putAwayTime);
        } else {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有数据');
        }
    }

    /**
     * 删除
     */
    public function delete(){
        $param = self::getHttpParam();
        $model = $this->model;

        if (empty($param->advertiseId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'advertiseId 不能为空');
        }

        $id = $param->advertiseId;
        Db::startTrans();
        try {
            $result = $model->where('id', $id)->update(['status' => 3]);
            if($result !== false){
                $info = $model->where('id', $id)->find();
                $res = $this->updatePutAwayTime($info, 2);
                if($res === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::MSG_ERROR, '更新上架时间失败');
                }

                // Query执行后的操作
                $model->_after_delete($id);

                Db::commit();
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, '删除成功');
            }else{
                Db::rollback();
                return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $model->getError());
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $e->getMessage());
        }
    }

    /**
     * 上架/下架
     */
    public function handleShelf(){
        $param = self::getHttpParam();
        $model = $this->model;

        if (empty($param->advertiseId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'advertiseId 不能为空');
        }
        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 不能为空');
        }
        if (!in_array($param->type, [1, 2])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
        }

        $id = $param->advertiseId;
        $info = $model->where('id', $id)->find();
        Db::startTrans();
        try {
            if($param->type == 1){
                // 上架
                $data['status'] = 1;
                $result = $model->allowField(true)->save($data, ['id' => $id]);
            }else{
                // 下架
                $data['status'] = 2;
                $result = $model->allowField(true)->save($data, ['id' => $id]);
            }

            if($result !== false){
                $res = $this->updatePutAwayTime($info, $param->type);
                if($res === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::MSG_ERROR, '更新上架时间失败');
                }

                Db::commit();
                return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, '操作成功');
            }else{
                Db::rollback();
                return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $model->getError());
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $e->getMessage());
        }
    }

    /**
     * 更新上架时间
     */
    public function updatePutAwayTime($info, $type = 1){
        return true;

        // TODO
        if(!$info){
            return false;
        }
        $model = $this->model;
        $ids = db('advertiselocalconnect')->where(['advertiseLocalId' => $info['advertiseLocalId']])->field('advertiseId')->select();
        $ids = array_column($ids, 'advertiseId');
        $where = [
            'id' => ['in', $ids],
            'putAwayTime' => ['gt', $info['putAwayTime']],
            'status' => 1
        ];
        $circleTime = $info['circleTime'];
        $list = $model->where($where)->field('id, putAwayTime')->select();

        Db::startTrans();
        try {
            $res = true;
            foreach ($list as $item) {
                if($type == 1){
                    $putAwayTime = strtotime($item['putAwayTime']) + $circleTime * 24*3600;
                }else{
                    $putAwayTime = strtotime($item['putAwayTime']) - $circleTime * 24*3600;
                }
                $putAwayTime = date('Y-m-d H:i:s');
                $data = [
                    'putAwayTime' => $putAwayTime
                ];
                $result = $model->allowField(true)->save($data, ['id' => $item['id']]);
                if($result === false){
                    $res = false;
                }
            }

            if($res === false){
                Db::rollback();
                return false;
            }

            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }
    }

    /**
     * 获取广告位
     */
    public function getAdvertiselocalTree(){
        $param = self::getHttpParam();

        if (empty($param->type) && $param->type != 0) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 不能为空');
        }
        if (!in_array($param->type, [0, 1])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
        }

        $where = [
            'type' => $param->type
        ];
        $options = Advertiselocal::where($where)->field('id,advertiseLocalName')->select();

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $options);
    }

}